package com.czy.owner.ui;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.print.PrintJob;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

import com.czy.owner.R;
import com.czy.owner.db.UserHelper;
import com.czy.owner.global.Constants;
import com.czy.owner.entity.AdvertisementEntity;
import com.czy.owner.utils.AdvertisementManager;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.easemob.cases.MessageHelper;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;

import org.xutils.common.Callback;
import org.xutils.x;

import java.io.File;

import butterknife.BindView;


/**
 * Created by King on 2017-04-25
 */

public class SplashActivity extends BaseActivity {
    @BindView(R.id.iv_splash)
    ImageView ivSplash;
    private final String TAG = getClass().getSimpleName();
    private int oldVersionCode = 0, currentVersionCode = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
//        去掉窗口标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 隐藏状态栏,全屏显示
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_splash;
    }

    @Override
    protected void initInjector() {
        UserHelper.getInstance().setIsLogined(initLoginState());
    }

    @Override
    protected void initViews() {
        AdvertisementManager.getInstance().getAdvertisementConfig(SplashActivity.this);
        oldVersionCode = (int) SharedPreferencesUtils.getParam(SplashActivity.this, Constants.SHARED_PREFERENCES_KEY_VERSION_CODE, 0);
        currentVersionCode = PhoneUtils.getVersionCode(SplashActivity.this);

        AdvertisementEntity splashInformation = AdvertisementManager.getInstance().getAdvertisementInformation(SplashActivity.this, AdvertisementManager.AD_TYPE_START_PAGE);

        if (splashInformation != null) {
            x.image().loadFile(splashInformation.getPicUrl() + "-1920%7C1080", null, new Callback.CacheCallback<File>() {
                private boolean hasCache = false;

                @Override
                public boolean onCache(File result) {
                    if (result.exists()) {
                        Bitmap bitmap = BitmapFactory.decodeFile(result.getPath());
                        ivSplash.setImageBitmap(bitmap);
                        hasCache = true;
                    }
                    return false;
                }

                @Override
                public void onSuccess(File result) {
                    if (result.exists()) {
                        Bitmap bitmap = BitmapFactory.decodeFile(result.getPath());
                        ivSplash.setImageBitmap(bitmap);
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    if (!hasCache) {
                        ivSplash.setImageResource(R.mipmap.splash_img);
                    }
                }

                @Override
                public void onCancelled(CancelledException cex) {
                    if (!hasCache) {
                        ivSplash.setImageResource(R.mipmap.splash_img);
                    }
                }

                @Override
                public void onFinished() {

                }
            });
        } else {
            ivSplash.setImageResource(R.mipmap.splash_img);
        }

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                AdvertisementEntity advertisementEntity = AdvertisementManager.getInstance().getAdvertisementInformation(SplashActivity.this, AdvertisementManager.AD_TYPE_ADV_PAGE);
                if (oldVersionCode == 0 || oldVersionCode < currentVersionCode) {
                    startActivity(new Intent(SplashActivity.this, AppGuideActivity.class));
                    SharedPreferencesUtils.setParam(SplashActivity.this, Constants.SHARED_PREFERENCES_KEY_VERSION_CODE, currentVersionCode);
                    finish();
                } else if (advertisementEntity != null) {
                    MyLog.e("yang","11111");
                    startActivity(new Intent(SplashActivity.this, AdvertisingActivity.class));
                    finish();
                } else {
                    intoMainActivity();
                }
            }
        }, 2000);
    }

    @Override
    protected void updateViews() {

    }


    //主页
    private void intoMainActivity() {
        if (UserHelper.getInstance().isLogined()) {
            MessageHelper.getInstance().reset();
            MyLog.d("King", UserHelper.getInstance().getUserInfoModel(this).getImKey() + "|" + UserHelper.getInstance().getUserInfoModel(this).getImPasswd());
            EMClient.getInstance().login(UserHelper.getInstance().getUserInfoModel(this).getImKey(), UserHelper.getInstance().getUserInfoModel(this).getImPasswd(), new EMCallBack() {//回调
                @Override
                public void onSuccess() {
                    MessageHelper.getInstance().getUserProfileManager().setCurrentUser(UserHelper.getInstance().getUserInfoModel(getApplicationContext()).getNickName(),
                            UserHelper.getInstance().getUserInfoModel(getApplicationContext()).getUserLogo());

                    EMClient.getInstance().groupManager().loadAllGroups();
                    EMClient.getInstance().chatManager().loadAllConversations();

                    MyLog.d("King", "登录聊天服务器成功！" + UserHelper.getInstance().getUserInfoModel(SplashActivity.this).getImKey() + "|" + UserHelper.getInstance().getUserInfoModel(SplashActivity.this).getImPasswd());
                    startActivity(new Intent(SplashActivity.this, MainActivity.class));
                    finish();
                }

                @Override
                public void onProgress(int progress, String status) {

                }

                @Override
                public void onError(int code, String message) {
                    MyLog.d("King", "登录聊天服务器失败！" + code + "|" + message);
                    startActivity(new Intent(SplashActivity.this, MainActivity.class));
                    finish();
                }
            });
        } else {
            startActivity(new Intent(SplashActivity.this, MainActivity.class));
            finish();
        }
    }


    //用户是否存在判断
    private boolean initLoginState() {
        if (UserHelper.getInstance().getSessionInfoModel(this) == null || UserHelper.getInstance().getUserInfoModel(this) == null || UserHelper.getInstance().getOwnerInfoModel(this) == null) {
            return false;
        } else {

            MyLog.i(TAG, UserHelper.getInstance().getSessionInfoModel(this).toString());
            MyLog.i(TAG, UserHelper.getInstance().getUserInfoModel(this).toString());
            MyLog.i(TAG, UserHelper.getInstance().getOwnerInfoModel(this).toString());
            return true;
        }
    }
}
